package util;

import java.util.ArrayList;
import java.util.List;

import common.Constant;

import model.Item;

public class BinarySort {
	
	public static void SortItem(List<Item> list,Item item){
		int first=0;
		int end=list.size()-1;
		int mid=0;
		if (-1==end){
			list.add(item);
			return;
		}
		
		while(first<end){
			mid=(first+end)/2;
			if(item.getMatchdegree()<list.get(mid).getMatchdegree())
				first=mid+1;
			else if(item.getMatchdegree()>list.get(mid).getMatchdegree())
				if(0==mid)
					end=0;
				else
					end=mid-1;
			else 
				first=end=mid;
		}
		if (first==end){
			if(item.getMatchdegree()<=list.get(first).getMatchdegree())
				list.add(first+1, item);
			else if(item.getMatchdegree()>list.get(first).getMatchdegree())
				list.add(first,item);
				
		}
		else{
			list.add(first+1, item);
		}
	}
	
	public static void insertItem(List<Item> list,Item item,List<String> tags){
		
		for(String tag:tags){
			if (item.tags.contains(tag)){
				item.setMatchdegree(item.getMatchdegree()+Constant.TagWeight);
				item.setMatchedTags(item.getMatchedTags()+" "+tag);
			}			
			if (item.getName().contains(tag) || item.getName_py().contains(PinYin.getPinyin(tag))){
				item.setMatchdegree(item.getMatchdegree()+Constant.NameWeight);				
			}
		}
		SortItem(list,item);
	}
	
	public static void main(String[] args) {
		
		List<Item>il=new ArrayList<Item>();
		
		SortItem(il, new Item(1,10));
		SortItem(il, new Item(2,11));
		SortItem(il, new Item(3,91));
		SortItem(il, new Item(4,61));
		SortItem(il, new Item(5,11));
		SortItem(il, new Item(6,12));
		SortItem(il, new Item(7,11));
		SortItem(il, new Item(8,10));
		SortItem(il, new Item(9,11));
		System.out.println(il.size());
		for(int i=0;i<il.size();i++){
			Item item=il.get(i);
			System.out.println("i:"+i+"id:"+item.getId()+"  md:"+item.getMatchdegree());
		}
	
	}
	
}


